<template>
    <div class="goods-type-edit">
        <!--图片处理区-->
        <Row :gutter="20">
            <Col span="10" class="magi">
                <Card class="goods-type-edit-left">
                    <p slot="title">
                        <Icon type="ios-cloud-upload"></Icon> 请上传 <a>商品分类</a> 图标 (每次只能上传一张图片)
                    </p>
                    <!--拖拽区-->
                    <Upload accept="image/png, image/jpeg, image/gif, image/jpg" type="drag" action="?" :before-upload="handleBeforeUpload">
                        <div class="upImg">
                            <a><Icon type="ios-cloud-upload" size="52"></Icon></a>
                            <p>点击或将图片拖拽到这里上传</p>
                        </div>
                    </Upload>
                </Card>
            </Col>
            <Col span="14" class="magi">
                <Card class="goods-type-edit-right">
                    <p slot="title">
                        <Icon type="ios-photos-outline"></Icon> 图片裁剪及预览
                    </p>
                    <!--裁剪区-->
                    <Row :gutter="10">
                        <Col span="12">
                            <!--裁剪区-->
                            <div class="cropper">
                                <img id="cropimg" :src="img" alt="">
                                <a><Icon type="crop" size="52"></Icon></a>
                                <p>图片裁剪区</p>
                            </div>
                        </Col>
                        <Col span="12">
                            <!--展示区-->
                            <Row type="flex" justify="center" align="middle" class="preview-con">
                                <div id="preview">
                                    <a><Icon type="ios-photos-outline" size="52"></Icon></a>
                                    <p>图片预览区</p>
                                </div>
                            </Row>
                        </Col>
                    </Row>
                </Card>
            </Col>
        </Row>
        <!--表单区-->
        <Card>
            <p slot="title">
                <Icon type="edit"></Icon> 请编辑 <a>商品分类</a> 属性<Switch></Switch>
            </p>
            <!--表单-->
            <div class="formCon">
                <Form ref="formValidate" :model="formItem" :label-width="90" label-position="left" :rules="rules">
                    <FormItem label="是否显示">
                        <i-switch v-model="formItem.switch" size="large">
                            <span slot="open">显示</span>
                            <span slot="close">隐藏</span>
                        </i-switch>
                    </FormItem>
                    <FormItem label="商品分类名" prop="input">
                        <Input v-model="formItem.input" placeholder="请输入商品分类名" type="text"></Input>
                    </FormItem>
                    <FormItem label="排序号"  prop="num">
                        <Input number v-model="formItem.num" placeholder="请输入排序号"></Input>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" @click="handleSubmit">提交</Button>
                        <Button type="ghost" @click="handleReset" style="margin-left: 8px">重置</Button>
                    </FormItem>
                </Form>
            </div>
        </Card>
    </div>
</template>
<script>
    import Cropper from 'cropperjs';
    import '../../../my-components/image-editor/cropper.min.css';
    export default {
        name:"goods-type-edit",
        data(){
            const validateNum = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('排序号不能为空'));
                }
                // 模拟异步验证效果
                setTimeout(() => {
                    if (!Number.isInteger(value)) {
                        callback(new Error('请输入数字值'));
                    } else {
                        callback();
                    }
                }, 1000);
            };
            const validateName = (rule, value,callback) => {
                if (!value) {
                    return callback(new Error('分类名不能为空'));
                }else{
                    callback();
                }
            }
            return{
                cropper:{},//
                formItem: {
                    input:"",
                    switch:true,
                    num:"",
                },
                rules:{
                    input: [
                        { required: true, validator: validateName, trigger: 'blur' }
                    ],
                    num: [
                        {required: true, validator: validateNum, trigger: 'blur' }
                    ]
                },
                timeImg:"",//临时存储的图片
                img:""
            }
        },
        mounted(){
            if(this.$route.query.isEdit){
                this.getEdit()
            }else{
                //新新增
                this.startCropper()
            }
        },
        methods:{
            getEdit(){
                this.getJsonData("Cat/getOneCatByCatId",{catId:this.$route.query.id})
                    .then((res)=>{
                        this.img=res.data.pic
                        this.formItem.input=res.data.catname
                        this.formItem.switch=res.data.isshow==1?true:false
                        this.formItem.num=parseFloat(res.data.catsort)
                        this.$nextTick(()=>{this.editCropper()})
                    })
            },
            //初始化cropper
            startCropper(){
                let img = document.getElementById('cropimg');
                this.cropper = new Cropper(img, {
                    autoCropArea:0.8,
                    aspectRatio: 1,
                    dragMode: 'move',
                    preview: '#preview',//展示区
                    restore: false,
                    center: false,
                    highlight: false,
                    cropBoxMovable: false,
                    toggleDragModeOnDblclick: false
                });
            },
            //编辑
            editCropper(){
                let img = document.getElementById('cropimg');
                this.cropper = new Cropper(img, {
                    autoCrop:false,
                    dragMode: 'move',
                    restore: false,
                    center: false,
                    highlight: false,
                    cropBoxMovable: false,
                    toggleDragModeOnDblclick: false,
                    zoomable:false,
                    movable:false,
                });
            },
            //上传之前的操作
            handleBeforeUpload(file){
                this.startCropper()
                if((Math.round(file.size/1024*100)/100)<2000){
                    this.caijianImg(file)
                }else{
                    this.$Notice.error({
                        title: '文件过大',
                        desc: '文件 '+file.name +'/'+(Math.round(file.size/1024*100)/100)+'KB'+'，请上传 2M 以内的图片。',
                        duration:4.5
                    });
                }
                //禁止默认上传
                return false
            },
            caijianImg(file){
                let reader = new FileReader();
                reader.onload = () => {
                    this.cropper.replace(reader.result);
                    this.timeImg=reader.result
                    reader.onload = null;
                };
                reader.readAsDataURL(file);
            },
            handleSubmit () {
                if(this.timeImg==""){
                    if(this.$route.query.isEdit){
                        this.$refs.formValidate.validate((valid) => {
                            if (valid) {
                                this.upImg()
                            } else {
                                //不做处理
                            }
                        })
                    }else{
                        this.$Message.error('请先上传图片');
                    }
                }else{
                    this.$refs.formValidate.validate((valid) => {
                        if (valid) {
                            this.upImg()
                        } else {
                            //不做处理
                        }
                    })
                }
            },
            handleReset () {
                this.$refs.formValidate.resetFields();
            },
            //上传图片
            upImg(){
                this.$Loading.start();
                this.upBaseImg("admin/upLoadImages",{image:this.cropper.getCroppedCanvas().toDataURL()})
                    .then((res) =>{
                        if(this.$route.query.isEdit){
                            this.submitPic(res.data.url)
                        }else{
                            this.editGoods(res.data.url)
                        }
                    })
            },
            //上传分类属性
            editGoods(url){
                this.getJsonData("Cat/addCat",{
                    parentId:this.$route.query.id,
                    isShow:this.formItem.switch?1:-1,
                    catName:this.formItem.input,
                    catSort:this.formItem.num,
                    pic:url
                })
                    .then((res)=>{
                        this.$Message.success("提交成功")
                    })
            },
            //确定提交
            submitPic(url){
                this.getJsonData("Cat/changeCat",{
                    catId:this.$route.query.id,
                    isShow:this.formItem.switch?1:-1,
                    catName:this.formItem.input,
                    catSort:this.formItem.num,
                    pic:url
                })
                    .then((res)=>{
                        this.$Message.success("提交成功")
                    })
            },
        }
    }
</script>
<style lang="less">
    @import "./goods-type-edit";
</style>